package com.study.it.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

import com.study.it.dao.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.reflect.*;
public class BaseDaoImpl<T> implements BaseDao<T>{
	Class<?> _class=null;//T.class走不通，用特殊的手法获取它
	
	public BaseDaoImpl()
	{
		_class=(Class<?>)((ParameterizedType)this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	protected SessionFactory fty=null;
	@Autowired
    public void setFty(SessionFactory fty) {
		this.fty = fty;
	}
	@Override
	public void refresh(T g) {
		fty.getCurrentSession().refresh(g);
	}

	@Override
	public void insert(T g) {
		fty.getCurrentSession().save(g);
	}

	@Override
	public void update(T g) {
		fty.getCurrentSession().update(g);
	}

	@Override
	public void delete(Serializable id) {
		this.delete(this.selectOne(id));//跟喜欢互相利用
	}

	@Override
	public void delete(T g) {
		fty.getCurrentSession().delete(g);
	}

	@Override
	public T loadOne(Serializable id) {
		return (T) fty.getCurrentSession().load(_class, id);
	}

	@Override
	public T selectOne(Serializable id) {
		return (T) fty.getCurrentSession().get(_class, id);
	}

	@Override
	public T selectOne(DetachedCriteria dc) {
		Criteria c=dc.getExecutableCriteria(fty.getCurrentSession());
		return (T) c.uniqueResult();
	}

	@Override
	public Object selectSingle(DetachedCriteria dc) {
		Criteria c=dc.getExecutableCriteria(fty.getCurrentSession());
		return c.uniqueResult();
	}

	@Override
	public List<T> selectList() {
		return this.selectList(false);//借力打力
	}

	@Override
	public List<T> selectList(boolean isCache) {
		 Criteria c= fty.getCurrentSession().createCriteria(_class);
		 c.setCacheable(isCache);
		 return c.list();
	}

	@Override
	public List<T> selectList(DetachedCriteria dc) {
		return this.selectList(dc,false);
	}

	@Override
	public List<T> selectList(DetachedCriteria dc, boolean isCache) {
		try {
			Criteria c = dc.getExecutableCriteria(fty.getCurrentSession());
			c.setCacheable(isCache);
			return c.list();
		}catch (Exception ex)
		{
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	@Override
	public List<T> selectList(DetachedCriteria dc, int start, int row) {
	   return 	this.selectList(dc,start,row,false);
	}

	@Override
	public List<T> selectList(DetachedCriteria dc, int start, int row, boolean isCache) {
		Criteria c=dc.getExecutableCriteria(fty.getCurrentSession());
		c.setCacheable(isCache);
		c.setFirstResult(start);//从第几行开始
		c.setMaxResults(row);//取多少行
		return c.list();
	}

	@Override
	public List<T> selectList(String hql, Object[] objects) {
		Query q=fty.getCurrentSession().createQuery(hql);
		int i=0;
		for(Object o:objects)
			q.setParameter(i++, o);
		return q.list();
	}
	
	
}





